/*
 * Copyright 2012-2013 EZC Group S.A. RCS Luxembourg B140949
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.yobidrive.y3.v1.client.http.handlers;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.yobidrive.y3.http.HttpResponseHandler;
import com.yobidrive.y3.utils.XMLUtils;
import com.yobidrive.y3.v1.model.DriveSecret;
import com.yobidrive.y3.v1.model.FinalizePairingResult;
import com.yobidrive.y3.v1.model.GetDriveListResult;
import com.yobidrive.y3.v1.model.GetUserConfigurationResult;
import com.yobidrive.y3.v1.model.KeyValue;
import com.yobidrive.y3.v1.model.Leaf;
import com.yobidrive.y3.v1.model.Member;
import com.yobidrive.y3.v1.model.Node;
import com.yobidrive.y3.v1.model.RequestChallengeResult;
import com.yobidrive.y3.v1.model.RequestSoftPairingResult;
import com.yobidrive.y3.v1.model.RequestTokenResult;
import com.yobidrive.y3.v1.model.Subscription;
import com.yobidrive.y3.v1.model.SubscriptionUsage;


public class GetUserConfigurationResponseHandler extends HttpResponseHandler<GetUserConfigurationResult>{

	static private final Logger logger = Logger.getLogger(GetUserConfigurationResponseHandler.class);
	
	@Override
	public GetUserConfigurationResult handleResponse(HttpResponse response)
			throws ClientProtocolException, IOException {
		
		//Call super to handle every error messages
		super.handleResponse(response);
		
		GetUserConfigurationResult result = new GetUserConfigurationResult();
		ArrayList<KeyValue> kvArray = new ArrayList<KeyValue>();
		
		//Parse XML response
		HttpEntity entity = response.getEntity();
		
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(entity.getContent());
			Element rootElement = doc.getDocumentElement(); 
			
			result.firstName 	= XMLUtils.getChildText(rootElement, "firstname");
			result.lastName 	= XMLUtils.getChildText(rootElement, "lastname");
			result.language 	= XMLUtils.getChildText(rootElement, "language");
			result.address		= XMLUtils.getChildText(rootElement, "address");
			result.city			= XMLUtils.getChildText(rootElement, "city");
			result.company		= XMLUtils.getChildText(rootElement, "company");
			result.country		= XMLUtils.getChildText(rootElement, "country");
			result.rcsnumber	= XMLUtils.getChildText(rootElement, "rcsnumber");
			result.vatnumber	= XMLUtils.getChildText(rootElement, "vatnumber");
			result.vattype		= XMLUtils.getChildText(rootElement, "vattype");
			result.zip			= XMLUtils.getChildText(rootElement, "zip");
			result.complete		= XMLUtils.getChildText(rootElement, "complete");
			
			//Parse subscription
			Element subscriptionElement = XMLUtils.getChildByName(rootElement, "subscription");
			if ( subscriptionElement != null  ) {
				Subscription subscription = new Subscription();
				subscription.subscriptionid = XMLUtils.getChildText(subscriptionElement, "subscriptionid");
				subscription.validityFrom = XMLUtils.getChildText(subscriptionElement, "validityfrom");
				subscription.validityTo = XMLUtils.getChildText(subscriptionElement, "validityto");
				subscription.isTrial = XMLUtils.stringToBoolean(XMLUtils.getChildText(subscriptionElement, "istrial"), false);
				result.subscription = subscription;
				//Parse usage if present
				Element usageElement = XMLUtils.getChildByName(subscriptionElement, "usage");
				if ( usageElement != null ) {
					NodeList usageElts = usageElement.getElementsByTagName("subscriptionusage");
					SubscriptionUsage[] subUsage = new SubscriptionUsage[usageElts.getLength()];
					for ( int i=0 ; i<usageElts.getLength(); i++) {
						org.w3c.dom.Node childNode = usageElts.item(i);
						SubscriptionUsage u = new SubscriptionUsage();
						u.key = XMLUtils.getChildText(childNode, "key");
						u.current = XMLUtils.getChildText(childNode, "current");
						u.maximum = XMLUtils.getChildText(childNode, "maximum");
						u.remaining = XMLUtils.getChildText(childNode, "remaining");
						subUsage[i] = u;
					}
					result.subscription.usage = subUsage;
 				}
			}

			//Parse next subscriptions
			Element nextElement = XMLUtils.getChildByName(rootElement, "nextsubscriptions");
			if ( nextElement != null ) {
				NodeList subs = nextElement.getElementsByTagName("subscription");
				Subscription[] nextSubs = new Subscription[subs.getLength()];
				for ( int i=0; i<subs.getLength() ; i++) {
					org.w3c.dom.Node childNode = subs.item(i);
					Subscription subscription = new Subscription();
					subscription.subscriptionid = XMLUtils.getChildText(childNode, "subscriptionid");
					subscription.validityFrom = XMLUtils.getChildText(childNode, "validityfrom");
					subscription.validityTo = XMLUtils.getChildText(childNode, "validityto");
					nextSubs[i] = subscription;
				}
				result.nextSubscriptions = nextSubs;
			}
			
			NodeList children = rootElement.getElementsByTagName("keyvalue");
			for ( int i=0; i<children.getLength() ; i++) {
				org.w3c.dom.Node childNode = children.item(i);
				
				KeyValue kv = new KeyValue();
				kv.key 		= XMLUtils.getChildText(childNode, "key");
				kv.value	= XMLUtils.getChildText(childNode, "value");	
				kvArray.add(kv);
			}
			
			KeyValue[] resArray = new KeyValue[kvArray.size()];
			kvArray.toArray(resArray);
			result.keyValues = resArray;
			
		} catch (Exception ex) {
			logger.error("Error handling response",ex);
			return null;
		}
		return result;
	}

	
	
}
